/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


// THIS CLASS IS LIKELY TO BE REPLACED BY MULTICHANNELED AUDIO

package com.qb9.flashlib.audio
{
	import flash.events.Event;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;

	/**
	 * Provides a simple API for the multiple operations perfomed on sounds.
	 * 
	 * @see flash.media.Sound
	 * @see flash.media.SoundChannel
	 * @see flash.media.SoundTransform
	 */ 

	public class Audio extends Playable
	{
		protected var sound:Sound;
		protected var channel:SoundChannel;
		protected var transform:SoundTransform;
		
		public function Audio(sound:Sound, id:String = null)
		{
			super(id);
			
			this.sound = sound;
			this.transform = new SoundTransform();
		}
		
		/* Properties */
		
		/** @inheritDoc */
		public override function get length() : Number
		{
			return sound.length;
		}
		
		/** @inheritDoc */
		public override function get position() : Number
		{
			return channel ? channel.position : 0;
		}
		
		/** @inheritDoc */
		public override function get volume() : Number
		{
			return transform.volume;
		}
		
		/** @inheritDoc */
		public override function set volume(vol:Number) : void
		{
			super.volume = vol;
			if (!muted)
				transform.volume = vol;
				
			if (channel)
				channel.soundTransform = this.transform;		
		}
		
		/** @inheritDoc */
		public override function loop(loops:int = int.MAX_VALUE) : void
		{
			super.loop(loops);
			
			// Make sure everything is garbage collected
			if (channel)
			{
				channel.removeEventListener(Event.SOUND_COMPLETE, _onPlayComplete);
				channel = null;
			}

			channel = sound.play(this.lastPos, loops, transform);
			channel.addEventListener(Event.SOUND_COMPLETE, _onPlayComplete);
		}
		
		/** @inheritDoc */
		public override function stop() : void
		{
			super.stop();
			if (channel)
				channel.stop();
		}
		
		/** @inheritDoc */
		public override function pause() : void
		{
			super.pause();
			if (channel)
				channel.stop();			
		}
		
		/** @inheritDoc */
		public override function dispose() : void
		{
			stop();
			
			if (channel)
				channel.removeEventListener(Event.SOUND_COMPLETE, _onPlayComplete);

			sound = null;
			transform = null;
			channel = null;
		}
	}
}
